<?php
// Deals with saving a prim's inventory 

require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
include(ABS_PATH . "misc/functions.php");

_log(__FILE__ . " - line " . __LINE__ . " We received: " . print_r($REQUEST, TRUE));

if ($_REQUEST['signature'])
{	
	// check for valid signature
	// try to calculate the signature
	if (isset($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY']))
	{
			// this is coming from SL, so we have the object key
			$signature = md5($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . $_REQUEST['timestamp'] . ':9876') ;
	
			if ($signature != $_REQUEST['signature'])
			{
					header("HTTP/1.0 503 Service Unavailable");
					die("Signature does not match - hack attempt?");		
			}
							
	}
	
	try {
		$db = new PDO(PDO_PREFIX . SQLITE_DB_FILENAME);
	}
	
	catch(PDOException $e)
	{
		header("HTTP/1.0 503 Service Unavailable");
   		printf("Connect failed: %s\n", $e->getMessage());
   		_log(__FILE__ . " - line " . __LINE__ . ": Error connecting to database: " . $e->getMessage());
    	exit();
	}
	
	try {
		$db->exec("REPLACE INTO Inventory (`UUID`, `Name`, `Type`, `Permissions`, `LastUpdate`) VALUES ('" .
			$_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . "','" .
			addslashes($_REQUEST['name']) . "','" .
			$_REQUEST['itemType'] . "','" .
			$_REQUEST['permissions'] . "','" .
			$_REQUEST['timestamp'] . "')");
	}	

	catch(PDOException $e)
	{
		header("HTTP/1.0 503 Service Unavailable");
   		printf("REPLACE query failed: %s\n", $e->getMessage());
   		_log(__FILE__ . " - line " . __LINE__ . sprintf(": REPLACE query failed: %s\n", $e->getMessage())); 
    	exit();
	}
	
	header("HTTP/1.0 200 OK");
	header("Content-type: text/plain; charset=utf-8");
	echo "'" . $_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME'] . "' successfully updated!";
	_log(__FILE__ . " - line " . __LINE__ . ": Successfully updated " . $_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME'] . " with item " . print_r($_REQUEST, TRUE));
}
else
{
	 header("HTTP/1.0 503 Service Unavailable");
	 echo "Signature not found";
}